<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 600px;
      border: 1px solid #000;
    }
  </style>
</head>
<body>
  <!-- 用于存放聊天内容的 -->
  <div class="box"></div>
  <input type="text">
  <button>发送</button>

  <script>
    const name = prompt("请输入名字");
    const id = new Date().getTime();
    const box = document.querySelector(".box");
    const button = document.querySelector("button");
    const input = document.querySelector("input");

    // 创建websocket连接
    var ws = new WebSocket("ws://127.0.0.1:8080");

    // 监听连接打开
    ws.onopen = function(evt) { 
      console.log("Connection open ..."); 
      // 前端给后端发送
      // ws.send("Hello WebSockets!");
    };

    // 监听接受到后端信息
    ws.onmessage = function(evt) {
      // console.log(evt.data);
      // 关闭连接
      // ws.close();

      const { id2, name, value } = JSON.parse(evt.data)

      // 前端要把接受到的信息放到上面的容器里面
      if (id2 === id) {
        box.innerHTML += "<p style='text-align: right'>" + name + "说：" + value + "</p>";
      } else {
        box.innerHTML += "<p>" + name + "说：" + value + "</p>";
      }
      
    };

    // 监听连接关闭
    ws.onclose = function(evt) {
      console.log("Connection closed.");
    }; 



    button.onclick = () => {
      // console.log(input.value);
      // ws.send(name + "说：" + input.value);

      // websocket只能发送字符串
      ws.send(JSON.stringify({
        id2: id,
        name: name,
        value: input.value
      }))
      input.value = "";
    }
  </script>
</body>
</html>